#!/bin/bash

# 监控服务设置脚本 - 使用本地安装而非Docker
set -e

echo "📊 设置本地监控服务"
echo "===================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# 检测操作系统
detect_os() {
    if [[ "$OSTYPE" == "darwin"* ]]; then
        OS="macos"
        log_info "检测到 macOS 系统"
    elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
        OS="linux"
        log_info "检测到 Linux 系统"
    else
        OS="unknown"
        log_warning "未知操作系统，可能需要手动安装"
    fi
}

# 安装 Prometheus
install_prometheus() {
    log_info "安装 Prometheus..."
    
    if command -v prometheus > /dev/null; then
        log_success "Prometheus 已安装"
        return 0
    fi
    
    PROMETHEUS_VERSION="2.45.0"
    
    if [[ "$OS" == "macos" ]]; then
        if command -v brew > /dev/null; then
            brew install prometheus
            log_success "Prometheus 安装完成"
        else
            log_info "使用二进制文件安装 Prometheus..."
            curl -LO "https://github.com/prometheus/prometheus/releases/download/v${PROMETHEUS_VERSION}/prometheus-${PROMETHEUS_VERSION}.darwin-amd64.tar.gz"
            tar xvf "prometheus-${PROMETHEUS_VERSION}.darwin-amd64.tar.gz"
            sudo mv "prometheus-${PROMETHEUS_VERSION}.darwin-amd64/prometheus" /usr/local/bin/
            sudo mv "prometheus-${PROMETHEUS_VERSION}.darwin-amd64/promtool" /usr/local/bin/
            rm -rf "prometheus-${PROMETHEUS_VERSION}.darwin-amd64"*
            log_success "Prometheus 二进制安装完成"
        fi
    elif [[ "$OS" == "linux" ]]; then
        log_info "使用二进制文件安装 Prometheus..."
        curl -LO "https://github.com/prometheus/prometheus/releases/download/v${PROMETHEUS_VERSION}/prometheus-${PROMETHEUS_VERSION}.linux-amd64.tar.gz"
        tar xvf "prometheus-${PROMETHEUS_VERSION}.linux-amd64.tar.gz"
        sudo mv "prometheus-${PROMETHEUS_VERSION}.linux-amd64/prometheus" /usr/local/bin/
        sudo mv "prometheus-${PROMETHEUS_VERSION}.linux-amd64/promtool" /usr/local/bin/
        rm -rf "prometheus-${PROMETHEUS_VERSION}.linux-amd64"*
        log_success "Prometheus 二进制安装完成"
    fi
}

# 安装 Node Exporter
install_node_exporter() {
    log_info "安装 Node Exporter..."
    
    if command -v node_exporter > /dev/null; then
        log_success "Node Exporter 已安装"
        return 0
    fi
    
    NODE_EXPORTER_VERSION="1.6.0"
    
    if [[ "$OS" == "macos" ]]; then
        if command -v brew > /dev/null; then
            brew install node_exporter
            log_success "Node Exporter 安装完成"
        else
            log_info "使用二进制文件安装 Node Exporter..."
            curl -LO "https://github.com/prometheus/node_exporter/releases/download/v${NODE_EXPORTER_VERSION}/node_exporter-${NODE_EXPORTER_VERSION}.darwin-amd64.tar.gz"
            tar xvf "node_exporter-${NODE_EXPORTER_VERSION}.darwin-amd64.tar.gz"
            sudo mv "node_exporter-${NODE_EXPORTER_VERSION}.darwin-amd64/node_exporter" /usr/local/bin/
            rm -rf "node_exporter-${NODE_EXPORTER_VERSION}.darwin-amd64"*
            log_success "Node Exporter 二进制安装完成"
        fi
    elif [[ "$OS" == "linux" ]]; then
        log_info "使用二进制文件安装 Node Exporter..."
        curl -LO "https://github.com/prometheus/node_exporter/releases/download/v${NODE_EXPORTER_VERSION}/node_exporter-${NODE_EXPORTER_VERSION}.linux-amd64.tar.gz"
        tar xvf "node_exporter-${NODE_EXPORTER_VERSION}.linux-amd64.tar.gz"
        sudo mv "node_exporter-${NODE_EXPORTER_VERSION}.linux-amd64/node_exporter" /usr/local/bin/
        rm -rf "node_exporter-${NODE_EXPORTER_VERSION}.linux-amd64"*
        log_success "Node Exporter 二进制安装完成"
    fi
}

# 创建 Prometheus 配置目录
create_prometheus_config() {
    log_info "创建 Prometheus 配置..."
    
    mkdir -p ./monitoring/prometheus
    mkdir -p ./monitoring/data
    
    # 创建 Prometheus 配置文件
    cat > ./monitoring/prometheus/prometheus.yml << 'EOF'
global:
  scrape_interval: 15s
  evaluation_interval: 15s

rule_files:
  - "rules/*.yml"

scrape_configs:
  # Prometheus 自身
  - job_name: 'prometheus'
    static_configs:
      - targets: ['localhost:9090']

  # DevOps SmartBot 后端
  - job_name: 'devops-backend'
    static_configs:
      - targets: ['localhost:8000']
    metrics_path: /metrics
    scrape_interval: 30s

  # Node Exporter (系统监控)
  - job_name: 'node-exporter'
    static_configs:
      - targets: ['localhost:9100']

  # MongoDB Exporter (如果安装)
  - job_name: 'mongodb-exporter'
    static_configs:
      - targets: ['localhost:9216']
    scrape_interval: 30s

  # Redis Exporter (如果安装)
  - job_name: 'redis-exporter'
    static_configs:
      - targets: ['localhost:9121']
    scrape_interval: 30s

alerting:
  alertmanagers:
    - static_configs:
        - targets:
          - localhost:9093
EOF

    # 创建简单的告警规则
    mkdir -p ./monitoring/prometheus/rules
    cat > ./monitoring/prometheus/rules/devops.yml << 'EOF'
groups:
  - name: devops-smartbot
    rules:
      - alert: ServiceDown
        expr: up == 0
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "Service {{ $labels.job }} is down"
          description: "{{ $labels.job }} has been down for more than 1 minute."

      - alert: HighMemoryUsage
        expr: (node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes) / node_memory_MemTotal_bytes > 0.8
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "High memory usage detected"
          description: "Memory usage is above 80% for more than 5 minutes."

      - alert: HighCPUUsage
        expr: 100 - (avg by(instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "High CPU usage detected"
          description: "CPU usage is above 80% for more than 5 minutes."

      - alert: DiskSpaceLow
        expr: (node_filesystem_avail_bytes / node_filesystem_size_bytes) * 100 < 10
        for: 5m
        labels:
          severity: critical
        annotations:
          summary: "Disk space is running low"
          description: "Disk space is below 10% on {{ $labels.device }}."
EOF

    log_success "Prometheus 配置文件已创建"
}

# 启动监控服务
start_monitoring_services() {
    log_info "启动监控服务..."
    
    # 启动 Node Exporter
    if command -v node_exporter > /dev/null; then
        log_info "启动 Node Exporter..."
        nohup node_exporter --web.listen-address=":9100" > ./monitoring/data/node_exporter.log 2>&1 &
        NODE_EXPORTER_PID=$!
        echo $NODE_EXPORTER_PID > .node_exporter.pid
        
        sleep 2
        if ps -p $NODE_EXPORTER_PID > /dev/null; then
            log_success "Node Exporter 启动成功 (端口: 9100)"
        else
            log_warning "Node Exporter 启动失败"
        fi
    fi
    
    # 启动 Prometheus
    if command -v prometheus > /dev/null; then
        log_info "启动 Prometheus..."
        nohup prometheus \
            --config.file=./monitoring/prometheus/prometheus.yml \
            --storage.tsdb.path=./monitoring/data/prometheus \
            --web.console.templates=/usr/local/share/prometheus/consoles \
            --web.console.libraries=/usr/local/share/prometheus/console_libraries \
            --web.listen-address=":9090" \
            --storage.tsdb.retention.time=15d \
            > ./monitoring/data/prometheus.log 2>&1 &
        PROMETHEUS_PID=$!
        echo $PROMETHEUS_PID > .prometheus.pid
        
        sleep 3
        if ps -p $PROMETHEUS_PID > /dev/null; then
            log_success "Prometheus 启动成功 (端口: 9090)"
        else
            log_warning "Prometheus 启动失败，请检查日志: ./monitoring/data/prometheus.log"
        fi
    fi
}

# 验证服务状态
verify_services() {
    log_info "验证监控服务状态..."
    
    # 检查 Node Exporter
    if curl -f -s http://localhost:9100/metrics > /dev/null 2>&1; then
        log_success "Node Exporter 运行正常"
    else
        log_warning "Node Exporter 连接失败"
    fi
    
    # 检查 Prometheus
    if curl -f -s http://localhost:9090/-/healthy > /dev/null 2>&1; then
        log_success "Prometheus 运行正常"
    else
        log_warning "Prometheus 连接失败"
    fi
}

# 创建监控停止脚本
create_monitoring_stop_script() {
    cat > ./scripts/stop-monitoring.sh << 'EOF'
#!/bin/bash

echo "🛑 停止监控服务..."

# 停止 Prometheus
if [ -f .prometheus.pid ]; then
    PROMETHEUS_PID=$(cat .prometheus.pid)
    kill $PROMETHEUS_PID 2>/dev/null || true
    rm .prometheus.pid
    echo "✅ Prometheus 已停止"
fi

# 停止 Node Exporter
if [ -f .node_exporter.pid ]; then
    NODE_EXPORTER_PID=$(cat .node_exporter.pid)
    kill $NODE_EXPORTER_PID 2>/dev/null || true
    rm .node_exporter.pid
    echo "✅ Node Exporter 已停止"
fi

echo "🎉 监控服务已停止"
EOF
    chmod +x ./scripts/stop-monitoring.sh
}

# 显示监控状态
show_monitoring_status() {
    echo ""
    echo "📊 监控服务已启动！"
    echo "===================="
    echo ""
    echo "📈 Prometheus:     http://localhost:9090"
    echo "🖥️  Node Exporter:  http://localhost:9100/metrics"
    echo ""
    echo "📋 监控管理:"
    echo "   查看 Prometheus 日志: tail -f monitoring/data/prometheus.log"
    echo "   查看 Node Exporter 日志: tail -f monitoring/data/node_exporter.log"
    echo "   停止监控服务: ./scripts/stop-monitoring.sh"
    echo ""
    echo "📚 使用指南:"
    echo "   1. 访问 http://localhost:9090 查看 Prometheus 控制台"
    echo "   2. 在 Graph 页面执行 PromQL 查询"
    echo "   3. 查看 Alerts 页面监控告警状态"
    echo "   4. Status > Targets 页面查看监控目标状态"
    echo ""
}

# 主函数
main() {
    detect_os
    install_prometheus
    install_node_exporter
    create_prometheus_config
    start_monitoring_services
    verify_services
    create_monitoring_stop_script
    show_monitoring_status
}

# 错误处理
trap 'log_error "监控服务设置失败"' ERR

# 执行主函数
main "$@"